package com.pinyougou.sellergoods.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.dubbo.common.json.JSON;
import com.alibaba.dubbo.common.json.JSONArray;
import com.alibaba.dubbo.common.json.ParseException;
import com.github.pagehelper.PageHelper;
import com.pinyougou.mapper.*;
import com.pinyougou.pojo.*;
import entity.Goods;
import org.apache.ibatis.cache.TransactionalCacheManager;
import org.apache.zookeeper.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.pinyougou.pojo.TbGoodsExample.Criteria;
import com.pinyougou.sellergoods.service.GoodsService;

import entity.PageResult;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.rowset.spi.TransactionalWriter;

/**
 * 服务实现层
 *
 * @author Administrator
 */
@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private TbGoodsMapper goodsMapper;
    @Autowired
    private TbGoodsDescMapper goodsDescMapper;
    @Autowired
    private TbItemMapper itemMapper;
    @Autowired
    private TbSellerMapper sellerMapper;
    @Autowired
    private TbBrandMapper brandMapper;
    @Autowired
    private TbItemCatMapper itemCatMapper;

    /**
     * 查询全部
     */
    @Override

    public List<TbGoods> findAll() {
        return goodsMapper.selectByExample(null);
    }

    /**
     * 按分页查询
     */
    @Override
    public PageResult findPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<TbGoods> page = (Page<TbGoods>) goodsMapper.selectByExample(null);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 增加
     */
    @Override
    public void add(Goods goods) {
        TbGoods tbGoods = goods.getTbGoods();
        TbGoodsDesc tbGoodsDesc = goods.getTbGoodsDesc();
        //获取去goods的id
        Long goodsId = tbGoods.getId();
//获取seller的id
        String sellerId = tbGoods.getSellerId();
        tbGoodsDesc.setGoodsId(goodsId);
        tbGoods.setId(goodsId);
        goodsMapper.insert(tbGoods);
        goodsDescMapper.insert(tbGoodsDesc);
        List<TbItem> itemList = goods.getItemList();
//获取图片url
        String url = "";
        if (tbGoodsDesc.getItemImages() != null) {
            List<Map> list = com.alibaba.fastjson.JSON.parseArray(tbGoodsDesc.getItemImages(), Map.class);
            if (list.size() > 0) {
                url = (String) list.get(0).get("url");
            }

        }
//SPU名称
        String title = tbGoods.getGoodsName();
        if ("1".equals(tbGoods.getIsEnableSpec())) {
            for (TbItem tbItem : itemList) {
//获取spec
                Map<String, Object> map = com.alibaba.fastjson.JSON.parseObject(tbItem.getSpec(), Map.class);
                Set<String> keys = map.keySet();
                for (String key : keys) {
                    title += " " + map.get(key);
                }
                tbItem.setTitle(title);//设置商品标题
                tbItem.setImage(url);//设置图片url
                tbItem.setUpdateTime(new Date());//设置更新时间
                tbItem.setCreateTime(new Date());//设置创建时间
                tbItem.setCategoryid(tbGoods.getCategory3Id());//设置商品分类
                tbItem.setGoodsId(goodsId);//设置goods的id
                tbItem.setSellerId(sellerId);//设置seller的id
                setItemValues(tbItem,tbGoods);

            }
        } else {
            TbItem tbItem = new TbItem();
            //获取spec
            tbItem.setTitle(title);//设置商品标题
            tbItem.setPrice(tbGoods.getPrice());
            tbItem.setNum(99999);//设置库存数
            tbItem.setIsDefault("1");
            tbItem.setStatus("1");
            tbItem.setImage(url);//设置图片url
            tbItem.setUpdateTime(new Date());//设置更新时间
            tbItem.setCreateTime(new Date());//设置创建时间
            tbItem.setGoodsId(goodsId);//设置goods的id
            tbItem.setSellerId(sellerId);//设置seller的id
            tbItem.setSpec("{}");
            setItemValues(tbItem,tbGoods);
        }

    }
    private void setItemValues(TbItem tbItem,TbGoods tbGoods) {

        tbItem.setCategoryid(tbGoods.getCategory3Id());//设置商品分类
//            设置商家名称
        TbSeller seller = sellerMapper.selectByPrimaryKey(tbGoods.getSellerId());
        tbItem.setSeller(seller.getNickName());
//            设置品牌名称
        TbBrand tbBrand = brandMapper.selectByPrimaryKey(tbGoods.getBrandId());
        tbItem.setBrand(tbBrand.getName());
        tbItem.setStatus("0");
//            设置分类名称
        TbItemCat tbItemCat = itemCatMapper.selectByPrimaryKey(tbGoods.getCategory3Id());
        tbItem.setCategory(tbItemCat.getName());
        System.out.println(tbItem);
        itemMapper.insert(tbItem);
    }


    /**
     * 修改
     */
    @Override
    public void update(Goods goods) {//商品更新
//        获取TbGoods
        TbGoods tbGoods = goods.getTbGoods();
//        获取goodId
        Long goodsId = tbGoods.getId();
//        先删除
        goodsMapper.deleteByPrimaryKey(goodsId);
        goodsDescMapper.deleteByPrimaryKey(goodsId);
        TbItemExample tbItemExample = new TbItemExample();
        TbItemExample.Criteria criteria = tbItemExample.createCriteria();
        criteria.andGoodsIdEqualTo(goodsId);
        itemMapper.deleteByExample(tbItemExample);
//        删除结束
        add(goods);//执行添加方法
    }

    /**
     * 根据ID获取实体
     *
     * @param id
     * @return
     */
    @Override
    public Goods findOne(Long id) {
        Goods goods = new Goods();
        TbGoods tbGoods = goodsMapper.selectByPrimaryKey(id);
        TbGoodsDesc tbGoodsDesc = goodsDescMapper.selectByPrimaryKey(id);
        goods.setTbGoods(tbGoods);
        goods.setTbGoodsDesc(tbGoodsDesc);
        TbItemExample tbItemExample = new TbItemExample();
        TbItemExample.Criteria criteria = tbItemExample.createCriteria();
        criteria.andGoodsIdEqualTo(tbGoods.getId());
        List<TbItem> tbItems = itemMapper.selectByExample(tbItemExample);
        goods.setItemList(tbItems);
        return goods;
    }

    /**
     * 批量删除
     */
    @Override
    public void delete(Long[] ids) {
        for (Long id : ids) {
            TbGoods tbGoods = goodsMapper.selectByPrimaryKey(id);
            tbGoods.setIsDelete("1");
            goodsMapper.updateByPrimaryKey(tbGoods);
        }
    }


    @Override
    public PageResult findToPage(TbGoods goods, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        TbGoodsExample example = new TbGoodsExample();
        Criteria criteria = example.createCriteria();
        criteria.andIsDeleteIsNull();
        criteria.andAuditStatusEqualTo("1");
        if (goods != null) {
            if (goods.getSellerId() != null && goods.getSellerId().length() > 0) {
//                criteria.andSellerIdLike("%" + goods.getSellerId() + "%");
                criteria.andSellerIdEqualTo(goods.getSellerId());
            }
            if (goods.getGoodsName() != null && goods.getGoodsName().length() > 0) {
                criteria.andGoodsNameLike("%" + goods.getGoodsName() + "%");
            }
            if (goods.getAuditStatus() != null && goods.getAuditStatus().length() > 0) {
                criteria.andAuditStatusLike("%" + goods.getAuditStatus() + "%");
            }
            if (goods.getIsMarketable() != null && goods.getIsMarketable().length() > 0) {
                criteria.andIsMarketableLike("%" + goods.getIsMarketable() + "%");
            }
            if (goods.getCaption() != null && goods.getCaption().length() > 0) {
                criteria.andCaptionLike("%" + goods.getCaption() + "%");
            }
            if (goods.getSmallPic() != null && goods.getSmallPic().length() > 0) {
                criteria.andSmallPicLike("%" + goods.getSmallPic() + "%");
            }
            if (goods.getIsEnableSpec() != null && goods.getIsEnableSpec().length() > 0) {
                criteria.andIsEnableSpecLike("%" + goods.getIsEnableSpec() + "%");
            }
            if (goods.getIsDelete() != null && goods.getIsDelete().length() > 0) {
                criteria.andIsDeleteLike("%" + goods.getIsDelete() + "%");
            }

        }

        Page<TbGoods> page = (Page<TbGoods>) goodsMapper.selectByExample(example);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void isMarketable(String number, Long goodsId) {
        TbGoods tbGoods = goodsMapper.selectByPrimaryKey(goodsId);
        tbGoods.setIsMarketable(number);
        goodsMapper.updateByPrimaryKey(tbGoods);
    }


    @Override
    public TbGoods findOneByOne(Long id) {
        TbGoods tbGoods = goodsMapper.selectByPrimaryKey(id);
        return tbGoods;
    }

    @Override
    public List<TbGoods> findByStatus(String id) {
        TbGoodsExample tbGoodsExample = new TbGoodsExample();
        Criteria criteria = tbGoodsExample.createCriteria();
        criteria.andAuditStatusEqualTo(id);
        List<TbGoods> tbGoods = goodsMapper.selectByExample(tbGoodsExample);
        return tbGoods;
    }

    @Override
    public void check(String status, Long[] goodsids) {
        for (Long goodsid : goodsids) {
            TbGoods tbGoods = goodsMapper.selectByPrimaryKey(goodsid);
            tbGoods.setAuditStatus(status);
            goodsMapper.updateByPrimaryKey(tbGoods);
        }
    }

}
